package com.example.rumen;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class BeiJingTime extends AppCompatActivity {


    //主线程
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {//hander比喻为消息队列，线程间通信


        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0x01) {
                String time = (String) msg.obj;
                time_text.setText(time);
            }
        }
    };


    private TextView time_text;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_bei_jing_time);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        SharedPreferences sharedPreferences = getSharedPreferences("Hello", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        int count = sharedPreferences.getInt("count", 1);
        Toast.makeText(getApplicationContext(), "恭喜您第"+count+"次访问", Toast.LENGTH_SHORT).show();
        editor.putInt("count", ++count);
        editor.commit();





        time_text = findViewById(R.id.textView_0408);
        new Thread() {

            @Override
            public void run() {
                super.run();
                while (true) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//TODO 考
                    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); //TODO 考
                    String timeformat = simpleDateFormat.format(System.currentTimeMillis());//获取当前时间


                    Message message = new Message();
                    message.what = 0x01;
                    message.obj = timeformat;
                    handler.sendMessage(message);


                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }


            }
        }.start();


    }


}